<template>
  <form class="validate-form-container">
    <slot name="default"></slot>

    <div class="submit-area" @click.prevent="submitForm">
      <slot name="submit">
        <button type="submit" class="btn btn-primary">提交</button>
      </slot>
    </div>
  </form>
</template>

<script setup lang="ts">
import { onUnmounted, provide } from "vue";
import mitt from "mitt";
import type { ValidateFunc } from "../types";

const emit = defineEmits(["form-submit"]);
const emitter = mitt<{ "form-item-created": ValidateFunc }>();
provide("emitter", emitter);
let FuncArr: ValidateFunc[] = [];

const submitForm = () => {
  const result = FuncArr.map((func) => func()).every((result) => result);
  emit("form-submit", result);
};

const callback = (func?: ValidateFunc) => {
  if (func) {
    FuncArr.push(func);
  }
};

emitter.on("form-item-created", callback);

onUnmounted(() => {
  emitter.off("form-item-created", callback);
  FuncArr = [];
});
</script>

<style scoped></style>
